<template>
  <div class="page-prod-insight">
    <!-- 实时概况板块 -->
    <div class="realtime-situation">
      <div class="new-page-title">
        <!-- 左边 -->
        <div class="title-left">
          <p class="line" />
          <span class="text">{{ $t("dataAnalysis.commodityInsight") }}</span>
        </div>
        <div class="title-right">
          <el-input
            v-model="prodName"
            :placeholder="$t('dataAnalysis.searchProd')"
            clearable
            @keyup.enter="searchHandle"
          >
            <template #suffix>
              <el-icon @click="searchHandle">
                <Search />
              </el-icon>
            </template>
          </el-input>
        </div>
      </div>
      <!-- /栏目标题行 -->

      <!-- 商品概况列表 -->
      <div class="item-list">
        <el-form
          :inline="true"
          :model="dataForm"
          class="form-inline"
          @submit.prevent
        >
          <el-form-item :label="$t('brand.status')+':'">
            <el-select
              v-model="dataForm.status"
              clearable
              :placeholder="$t('dataAnalysis.activeArea')"
              @change="changeDataForm()"
            >
              <el-option
                :label="$t('dataAnalysis.allStatus')"
                :value="0"
              />
              <el-option
                :label="$t('dataAnalysis.selling')"
                :value="1"
              />
              <el-option
                :label="$t('dataAnalysis.inTheWarehouse')"
                :value="2"
              />
              <el-option
                :label="$t('dataAnalysis.soldOut')"
                :value="3"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <DateTypeSelect
              :date-options="dateOptions"
              :date-type="5"
              :show-title="false"
              @date-change="onDateChange"
            />
          </el-form-item>
        </el-form>
        <div class="export-btn">
          <el-button
            v-if="isAuth('flow:prod:effect')"
            type="primary"

            @click="exportFrom()"
          >
            {{ $t('order.export') }}
          </el-button>
        </div>
        <el-form
          :model="form"
          class="form-inline"
          @submit.prevent
        >
          <el-form-item :label="$t('dataAnalysis.saleIndicators')+':'">
            <el-checkbox-group
              v-model="form.saleIndex"
              :max="saleIndicatorsMax"
              @change="selectNumChange"
            >
              <el-checkbox
                :label="$t('dataAnalysis.exposureTimes')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.exposurePeoples')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.addCartNumbers')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.carNumbers')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.placeOrderPerson')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.paidNumbers')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.placeOrderNum')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.goodsPaid')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.placeOrderAmount')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.goodsPaidAmount')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.unitConversionRate')"
                name="saleIndex"
              />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item :label="$t('dataAnalysis.serviceIndicators')">
            <el-checkbox-group
              v-model="form.serviceIndex"
              :max="serviceIndicatorsMax"
              @change="selectNumChange"
            >
              <el-checkbox
                :label="$t('dataAnalysis.refundOrdersCounts')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.applyingForRefund')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.refundedCounts')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.refundedSuccessCounts')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.successfulRefundAmount')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.refundRate')"
                name="saleIndex"
              />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item
            :label="$t('dataAnalysis.serviceIndicators')"
            class="transparent-text"
          >
            <div
              id="maxSelectSpan"
              class="select-txt"
              style="color:#155bd4 !important;"
            >
              {{ $t("dataAnalysis.upTo8") }}
            </div>
            <div class="select-txt">
              {{ $t("dataAnalysis.selected") }} <span class="select-num-txt">{{ selectNum }}</span>/{{ $t("dataAnalysis.eightItems") }}
            </div>
          </el-form-item>
        </el-form>
        <span />
      </div>
      <!-- /商品概况列表 -->
      <!-- 说明文字板块 -->
      <div class="title-text-info">
        <div>{{ $t("dataAnalysis.descText1") }}{{ $t("dataAnalysis.descText1Content") }}</div>
        <div>{{ $t("dataAnalysis.descText2") }}</div>
      </div>
      <!-- /说明文字板块 -->
      <div class="prod-hid-txt">
        {{ $t("dataAnalysis.hideTips") }}
      </div>
    </div>
    <!-- /实时概况板块 -->
    <!-- 整体看板 -->
    <div class="whole-plate">
      <!-- 图表 -->
      <ProdTable
        :prod-data="prodData"
        style="width: 100%"
      />
      <!-- /图表 -->
      <!-- 分页 -->
      <el-pagination
        v-if="prodData.data.length"
        :current-page="page.pageIndex"
        :page-sizes="[5, 10, 20, 30, 50, 100]"
        :page-size="page.pageSize"
        :total="page.total"
        style="margin-top: 15px"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
      />
      <!-- /分页 -->
    </div>
    <!-- /整体看板 -->
  </div>
</template>

<script setup>
import { ElLoading, ElMessage } from 'element-plus'
import DateTypeSelect from '../components/date-type-select.vue'
import ProdTable from './components/prod-table.vue'
import { Debounce } from '@/utils/debounce'
import { isAuth } from '@/utils'
import Big from 'big.js'

const dateOptions = [
  {
    label: $t('dataAnalysis.todayRealTime'),
    value: 4
  },
  {
    label: $t('dataAnalysis.nearly7'),
    value: 5
  },
  {
    label: $t('dataAnalysis.nearly30'),
    value: 6
  },
  {
    label: $t('dataAnalysis.naturalDay'),
    value: 1
  },
  {
    label: $t('dataAnalysis.naturalMonth'),
    value: 3
  }
]
// 时间更新
// 1:今日实时 2:近七天 3:近30天 4:自然日 5:自然月
let dateType = 5
let dateRange = []
const onDateChange = (data) => {
  dateRange = data.dateRange
  switch (data.timeType) {
    case 4:
      dateType = 1
      break
    case 5:
      dateType = 2
      break
    case 6:
      dateType = 3
      break
    case 1:
      dateType = 4
      break
    case 3:
      dateType = 5
      break
  }
  prodData.dateValue = dateType
  getProdEffect(page)
}

const form = reactive({
  saleIndex: [], // 销售指标
  serviceIndex: [] // 服务指标
})
const sumData = ref([])
const selectNum = ref(0) // 选择指标的数量
watch([() => form.saleIndex, () => form.serviceIndex], () => {
  selectNum.value = form.serviceIndex.length + form.saleIndex.length
  sumData.value = []
  sumData.value = sumData.value.concat(form.serviceIndex).concat(form.saleIndex)
  prodData.sumData = sumData.value
}, { deep: true })

onMounted(() => {
  // 初始选择3个默认数据项
  form.saleIndex = [
    $t('dataAnalysis.exposureTimes'),
    $t('dataAnalysis.exposurePeoples')
  ]
  form.serviceIndex = [
    $t('dataAnalysis.refundOrdersCounts')
  ]
  selectNumChange()
})

/**
 * 获取商品概况数据
 */
const prodName = ref('')
const dataForm = reactive({
  group: 0,
  status: 0
})
const prodData = reactive({
  prodName: null, // 商品名称
  dateValue: null, // 时间的选择
  sumData: [], // 所有指标
  data: [], // 数据
  params: {
    shopId: null,
    dateType: 1,
    group: 0,
    status: 0,
    prodName: null,
    startTime: null,
    endTime: null
  }
}) // 商品数据
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 5 // 每页显示多少条
})
const getProdEffect = (pageParam) => {
  // 请求参数传给表格子组件
  const params = {}
  params.shopId = null
  params.dateType = dateType
  params.group = dataForm.group
  params.status = dataForm.status
  params.prodName = prodName.value
  params.startTime = dateRange[0]
  params.endTime = dateRange[1]
  prodData.params = params
  http({
    url: http.adornUrl('/platform/prodAnalysis/getProdEffect'),
    method: 'get',
    params: http.adornParams(
      {
        current: pageParam == null ? page.currentPage : pageParam.currentPage,
        size: pageParam == null ? page.pageSize : pageParam.pageSize,
        shopId: null,
        dateType,
        group: dataForm.group,
        status: dataForm.status,
        prodName: prodName.value,
        startTime: dateRange[0],
        endTime: dateRange[1]
      }
    )
  }).then(({ data }) => {
    if (data) {
      data.records.forEach(element => {
        if (element.singleProdRate > 0) {
          Big.DP = 2
          element.singleProdRate = new Big(element.singleProdRate).times(100).toFixed()
          element.refundSuccessRate = new Big(element.refundSuccessRate).times(100).toFixed()
        }
      })
      prodData.data = data.records
      page.total = data.total
    }
  })
}
/**
 * 搜索商品名称
 */
const searchHandle = () => {
  getProdEffect(page)
}
// 每页数
const sizeChangeHandle = (val) => {
  page.pageSize = val
  page.currentPage = 1
  getProdEffect(page)
}
// 当前页
const currentChangeHandle = (val) => {
  page.currentPage = val
  getProdEffect(page)
}
/**
 * 选择框改变
 */
const changeDataForm = () => {
  getProdEffect(page)
}

// 导出
const exportFrom = Debounce(() => {
  const loading = ElLoading.service({
    lock: true,
    target: '.page-prod-insight',
    customClass: 'export-load',
    background: 'transparent',
    text: $t('shop.exportIng')
  })
  http({
    url: http.adornUrl('/platform/prodAnalysis/prodEffectExport'),
    method: 'get',
    params: http.adornParams(
      {
        current: page.currentPage,
        size: page.pageSize,
        shopId: null,
        dateType,
        group: dataForm.group,
        status: dataForm.status,
        prodName: prodName.value,
        startTime: dateRange[0],
        endTime: dateRange[1]
      }
    ),
    responseType: 'blob'
  }).then(({ data }) => {
    loading.close()
    const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
    const fileName = $t('dataAnalysis.commodityInsight') + '.xlsx'

    const elink = document.createElement('a')
    if ('download' in elink) { // 非IE下载
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else { // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
    ElMessage({
      message: $t('shop.exportSuccess'),
      type: 'success',
      duration: 1500
    })
  }).catch(() => {
    loading.close()
  })
})
/**
 * 动态修改最大可选数
 */
const serviceIndicatorsMax = ref(8) // 服务指标最大可选
const saleIndicatorsMax = ref(8) // 销售指标最大可选
const selectNumChange = () => {
  const num = 8 - (form.saleIndex.length + form.serviceIndex.length)
  if (num <= 0) {
    saleIndicatorsMax.value = form.saleIndex.length
    serviceIndicatorsMax.value = form.serviceIndex.length
  } else {
    saleIndicatorsMax.value = 8
    serviceIndicatorsMax.value = 8
  }
}

</script>

<style lang="scss" scoped>
.page-prod-insight {
  // eslint-disable-next-line vue-scoped-css/no-unused-selector
  .el-form-item {
    margin-bottom: 20px;
  }
  .item-list {
    background: #F7F8FA;
    margin: 20px 0 20px;
    padding-top: 20px;
    padding-bottom: 10px;
    position: relative;
    .form-inline {
      margin-left: 20px;
    }
  }

  .title-text-info {
    background: rgba(246, 192, 35, 0.06);
    border: 1px solid #F6C023;
    padding: 18px;
    div {
      font-size: 12px;
      line-height: 18px;
      color: #666;
      &:first-child {
        margin-bottom: 12px;
      }
    }
  }
  .title-left {
    text-align: left;
    display: flex;
    align-items: center;
    width: 80%;
  }
  .title-right {
    text-align: right;
    display: inline;
    width: 20%;
  }

  /**
  整体看板
   */
  .whole-plate {
    margin: 15px 0 30px;
  }
  .transparent-text :deep(.el-form-item__label) {
    color: transparent;
    .select-txt {
      font-size: 12px;
      color: #999999;
      display: inline-block;
      &:first-child {
        color: #155bd4;
      }
      .select-num-txt {
        color: #155BD4;
      }
    }
  }

  .prod-hid-txt {
    margin-top: 25px;
    font-size: 12px;
    color: #666666;
  }

  .export-btn {
    right: 10px;
    position: absolute;
    top: 18px;
  }
  :deep(.export-load) {
    top: -50% !important;
  }
}

</style>
